(* C:\Users\hp\Desktop\bravo_j\polynome.ml *)

let rec power x n = 
	match n with 0 -> 1
		| n -> x * power x (n-1)
                | _ -> invalid_arg "Le coefficient est negatif";;

let rec application poly x =
	match poly with
		[]           -> 0
		|(c,d)::poly -> c * (power x d) + application poly x;; 

let rec add poly1 poly2 = 
	match (poly1, poly2) with
		([],[])                    -> []
		|(p1,[])                   -> p1
		|([],p2)                   -> p2
		|((c1,d1)::p1,(c2,d2)::p2) -> 
			if d1 = d2 then 
				   if c1 + c2 <> 0 then (c1+c2,d2):: add p1 p2 
				                   else add poly1 poly2
			           else if d1 < d2 then (c1,d1) :: add p1 ((c2,d2)::p2)
			                           else (c2,d2) :: add ((c1,d1)::p1) p2 ;;	

let rec soustract poly1 poly2 = 
	match (poly1, poly2) with
		([],[])                    -> []
		|(p1,[])                   -> p1
		|([],(a,b)::p2)            -> (-a,b) :: soustract [] p2
		|((c1,d1)::p1,(c2,d2)::p2) -> 
			if d1 = d2 then 
				if c1 - c2 <> 0 then (c1-c2,d2):: add p1 p2 
				                else add poly1 poly2
			        else if d1 < d2 then (c1,d1) :: add p1 ((c2,d2)::p2)
			                        else (0-c2,d2) :: add ((c1,d1)::p1) p2 ;;

let rec deriv poly = 
	match poly with
		[]           -> []
		|(c,d)::poly -> (c*d,d-1) :: deriv poly;;

